package com.dify.tool.common.config;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author shl
 * @date 2024-07-01
 */
@Slf4j
@Configuration
public class MybatisPlusConfiguration {
    @Bean
    public BaseMetaObjectHandler metaObjectHandler() {
        log.info("配置mybatis-plus自动插入时间拦截器");
        return new BaseMetaObjectHandler();
    }

    /**
     * 新的分页插件,一缓和二缓遵循mybatis的规则,
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        String dbType = DbType.MYSQL.getDb();
        if (StrUtil.equals(DbType.MYSQL.getDb(), dbType)) {
            interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        } else if (StrUtil.equals(DbType.MARIADB.getDb(), dbType)) {
            interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MARIADB));
        } else if (StrUtil.equals(DbType.ORACLE.getDb(), dbType)) {
            interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.ORACLE));
        } else if (StrUtil.equals(DbType.ORACLE_12C.getDb(), dbType)) {
            interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.ORACLE_12C));
        } else if (StrUtil.equals(DbType.DB2.getDb(), dbType)) {
            interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.DB2));
        } else if (StrUtil.equals(DbType.POSTGRE_SQL.getDb(), dbType)) {
            interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.POSTGRE_SQL));
        } else if (StrUtil.equals(DbType.SQL_SERVER2005.getDb(), dbType)) {
            interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.SQL_SERVER2005));
        } else if (StrUtil.equals(DbType.SQL_SERVER.getDb(), dbType)) {
            interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.SQL_SERVER));
        } else if (StrUtil.equals(DbType.DM.getDb(), dbType)) {
            interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.DM));
        } else {
            interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        }
        log.info("配置mybatis-plus分页插件拦截器，数据库 [{}]", dbType);
        return interceptor;
    }
}
